package de.kai_morich.simple_usb_terminal;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.FragmentActivity;

import cn.com.zt.camera.constant.CameraConstant;
import cn.com.zt.camera.controller.CameraControllerImpl;
import cn.com.zt.camera.listener.CodeAnalysisCallback;
import cn.com.zt.camera.listener.ImageSavedCallback;
import cn.com.zt.camera.listener.VideoSavedCallback;
import cn.com.zt.camera.view.FileOutputOptions;
import cn.com.zt.camera.view.PreviewLayout;
import cn.com.zt.camera.view.WatermarkOptions;
import cn.com.zt.camera.view.WatermarkPosition;

import java.io.File;
import java.util.ArrayList;
/**
 * @author : liujiacheng
 * @Date ：2025/7/10 14:44
 * @Description ：
 **/
public class ShootingActivity extends FragmentActivity {
    private PreviewLayout previewLayout;
    private Button takePicture, startRecord, switchCamera;
    private Button flashAuto, flashOn, flashOff;
    private final CameraControllerImpl controller = new CameraControllerImpl();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shooting);

        // 手动绑定所有视图
        previewLayout = findViewById(R.id.previewLayout);
        takePicture = findViewById(R.id.takePicture);
        startRecord = findViewById(R.id.startRecord);
        switchCamera = findViewById(R.id.switchCamera);
        flashAuto = findViewById(R.id.flashAuto);
        flashOn = findViewById(R.id.flashOn);
        flashOff = findViewById(R.id.flashOff);

        // 相机初始化
        previewLayout.bindToLifecycle(this);
        controller.bindCameraPreview(previewLayout);
        controller.startPreview();

        // 文件输出配置（与View Binding无关，保留原逻辑）
        String imageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/image/";
//        String videoDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/video/";
        // 图片保存到公共相册目录
//        String imageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/MyApp/";
        String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyAppImages/";
//        String imageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
// 视频保存到公共视频目录
        String videoDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/MyApp/";

// 确保目录存在
        new File(imageDir).mkdirs();
        new File(videoDir).mkdirs();
        FileOutputOptions option = new FileOutputOptions.Companion.FileOutputOptionsBuilder()
                .setImageOutputDirectory(imageDir)
                .createImageName(() -> System.currentTimeMillis() + ".jpg")
                .setVideoOutputDirectory(videoDir)
                .createVideoName(() -> System.currentTimeMillis() + ".mp4")
                .setVideoMaxDuration(10 * 1000)
                .build();
        previewLayout.setFileOutputOptions(option);

        // 水印配置（需动态添加视图）
        TextView watermark = new TextView(this);
        watermark.setText("测试水印水印");
        watermark.setTextSize(14f);
        watermark.setTextColor(getResources().getColor(android.R.color.white));
        WatermarkOptions watermarkOptions = new WatermarkOptions.Companion.WatermarkOptionsBuilder()
                .setWatermarkView(watermark)
                .setPreviewShowWaterMark(true)
                .setWatermarkPosition(new WatermarkPosition(CameraConstant.WATER_POSITION_CENTER, 150f, 200f))
                .setSaveWatermarkTofile(true)
                .build();
        previewLayout.setWatermarkOptions(watermarkOptions);

        // 按钮事件
        takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                controller.takePicture(new ImageSavedCallback() {
                    @Override public void onError(String message, int code) {
                        /* 处理错误 */
                        Log.e("onError",message+code+"");
                    }
                    @Override public void onImageSaved(Uri originUri, Bitmap bitmap, File watermarkFile) {
                        /* 保存成功 */
                        Log.e("onImageSaved",originUri.toString());
//                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//                        Uri contentUri = Uri.fromFile(watermarkFile);
//                        intent.setData(contentUri);
//                        sendBroadcast(intent);
                    }
                },watermarkOptions);
            }
        });

        startRecord.setOnClickListener(v -> {
            if (controller.isRecording()) {
                controller.stopRecord();
                startRecord.setText("start recording");
            } else {
                controller.startRecord(new VideoSavedCallback() {
                    @Override public void onVideoSaved(Uri uri, File watermarkFile) { startRecord.setText("start recording"); }
                    @Override public void onError(int videoCaptureError, String message, Throwable cause) { /* 处理错误 */ }
                    @Override public void onWatermarkVideoProgressing(int progress, long progressTime) { /* 进度更新 */ }
                }, watermarkOptions);
                startRecord.setText("stop recording");
            }
        });

        switchCamera.setOnClickListener(v -> controller.switchCamera());
        flashAuto.setOnClickListener(v -> controller.setFlashMode(CameraConstant.FLASH_MODE_AUTO));
        flashOn.setOnClickListener(v -> controller.setFlashMode(CameraConstant.FLASH_MODE_ON));
        flashOff.setOnClickListener(v -> controller.setFlashMode(CameraConstant.FLASH_MODE_OFF));
    }
}